/*
 * @Date: 2023-04-29 13:47:39
 * @LastEditors: fuzhuang
 * @LastEditTime: 2023-12-11 10:42:37
 * @FilePath: \golib\easydb\easydb.go
 * @Description:
 */
package easydb

import "gorm.io/gorm"

type Rows struct {
	Columns    []string
	ColumnType []string
	Rows       [][]any
}

func GetRows(db *gorm.DB, sql string) (rows *Rows, err error) {
	records, err := db.Raw(sql).Rows()
	if err != nil {
		return
	}
	rows = new(Rows)
	rows.Columns, err = records.Columns()
	if err != nil {
		return
	}
	n := len(rows.Columns)
	ct, err := records.ColumnTypes()
	if err != nil {
		return
	}
	rows.ColumnType = make([]string, n)
	for i := 0; i < n; i++ {
		rows.ColumnType[i] = ct[i].DatabaseTypeName()
	}
	valPtrs := make([]any, n)
	for records.Next() {
		vals := make([]any, n)
		for i := 0; i < n; i++ {
			valPtrs[i] = &vals[i]
		}
		err = records.Scan(valPtrs...)
		if err != nil {
			return
		}
		rows.Rows = append(rows.Rows, vals)
	}
	return
}
